package com.qingxin.sys.verifier;

import java.io.File;

import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.digester.Rule;
import org.xml.sax.Attributes;

/**
 * XML文件嵌套引用规则
 * 
 * @author JiWangli
 */
public class XMLImportRule extends Rule {
	
	private String pathattr;
	private String joinmethod;
	
	public XMLImportRule(String pathattr, String joinmethod) {
		this.pathattr = pathattr;
		this.joinmethod = joinmethod;
	}
	
	
	@Override
	public void begin(String namespace, String name, Attributes attributes) throws Exception {
		String path = attributes.getValue(pathattr);
		File file = null;
		if(path != null && path.length() > 0){
			if(path.startsWith("classpath:")){
				path = path.substring(10);
				try {
					file = new File(getClass().getResource(path).toURI());
				} catch (Exception e) {
				}
			}else if(path.startsWith("file:")){
				path = path.substring(5);
				if(path.startsWith("/") || path.matches("^[a-zA-Z]:[/\\\\].+")){
					file = new File(path);
				}
			}
			if(file == null || !file.isFile()){
				if(getDigester() instanceof XMLDigester && ((XMLDigester)getDigester()).getRootFilepath() != null){
					file = new File(((XMLDigester)getDigester()).getRootFilepath(), path);
				}else{
					file = new File(path);
				}
			}
		}
		if(file != null && file.isFile() && getDigester() instanceof XMLDigester){
			File rulesFile = ((XMLDigester)getDigester()).getRulesFile();
			if(rulesFile != null && rulesFile.isFile()){
				XMLDigester digester = new XMLDigester(rulesFile);
				digester.setSubstitutor(getDigester().getSubstitutor());
				
				Object object = digester.parse(file);
				Object target = getDigester().peek(0);
				
				MethodUtils.invokeExactMethod(target, joinmethod, object);
			}
		}
	}
	
}
